﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Microsoft.SmartDevice.Connectivity;
using WindowsPhone.Tools;
using System.Reflection;
using System.IO;
using System.IO.Compression;
using System.Windows.Threading;
using System.Xml;
using Manifest;


namespace EzDeploy
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        #region Vars
        string ManifestPath = @Environment.GetEnvironmentVariable("TEMP").ToString() + "\\Ezdeploy\\";
        bool isQuietInstal = false;
        bool IsClearing=false;

        bool onGoing;
        int remIndex;

        private string _version
        {
            get
            {
                return Properties.Settings.Default.version;
            }
            set
            {
                Properties.Settings.Default.version = value;
            }
        }
        private bool _isOperating;
        private bool isOperating
        {
            get
            {
                return _isOperating;
            }
            set
            {
                this.Dispatcher.Invoke((ThreadStart)delegate
                {
                    ProgressBarPanel.IsExpanded = value;
                });
                _isOperating = value;
            }
        }

        private Xap xap;
        private Xap _selectedXap;
        public Xap selectedXap
        {
            get
            {
                return _selectedXap;
            }
            set
            {
                _selectedXap = value;
            }
        }
        //private bool IsWillStop = false;

        private ListedXaps _xaps;
        public ListedXaps Xaps
        {
            get
            {
                return _xaps;
            }
            private set
            {
                _xaps = value;
            }
        }

        private ListedXaps _modifiedxaps;
        public ListedXaps ModifiedXaps
        {
            get
            {
                return _modifiedxaps;
            }
            private set
            {
                _modifiedxaps = value;
            }
        }

        private Task task_Connect, task_Unistall, task_SmartInstall;

        private string wpconnect_Path
        {
            get {return Properties.Settings.Default.wpconnect_Path;}
            set
            { 
                Properties.Settings.Default.wpconnect_Path = value;
                Properties.Settings.Default.Save();
            }
        }
        private string zune_Path
        {
            get { return Properties.Settings.Default.zune_Path; }
            set 
            { 
                Properties.Settings.Default.zune_Path = value;
                Properties.Settings.Default.Save();
            }
        }

        private string _currentDeviceName;
        private string CurrentDeviceName
        {
            set
            {
                if (value!=null)
                {
                    if (value == "Windows Phone Device")
                    {
                        _currentDeviceName = "Phone";
                    }
                    if (value == "Windows Phone Emulator")
                    {
                        _currentDeviceName = "Emulator";
                    }
                }
            }
            get
            {
                return _currentDeviceName;
            }
        }

        private RemoteApplicationEx _curSelectedInstalledApp;
        public RemoteApplicationEx CurSelectedInstalledApp
        {
            get { return _curSelectedInstalledApp; }
            set
            {
                if (_curSelectedInstalledApp != value)
                {
                    _curSelectedInstalledApp = value;

                    NotifyPropertyChanged("CurSelectedInstalledApp");
                }
            }
        }

        private WindowsPhoneDevice _device;
        public WindowsPhoneDevice Device
        {
            get { return _device; }
            set
            {
                if (_device != value)
                {
                    _device = value;

                    NotifyPropertyChanged("Device");
                }
            }
        }

        #endregion
        
        public MainWindow()
        {
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            InitializeComponent();
            Task task_Initial = new Task(() => Initial());
            task_Initial.Start();
        }

        #region Xap & Device Operation

        private void InstallXap(Xap _xap)
        {
            if (_device.Connected)
            {
                if (!isOperating)
                {
                    isOperating = true;
                    ChangeProgressBarIndeterminate(true);

                    Xaps.InstallSelectedXap(_xap);

                    ChangeProgressBarIndeterminate(false);
                    isOperating = false;
                    Xaps.IsWillStop = false;
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone,true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_notconnect, true);
            }
        }

        private void InstallXaps(ObservableCollection<Xap> _xaps)
        {
            if (_device.Connected)
            {
                if (!isOperating)
                {
                    isOperating = true;
                    foreach (Xap item in Xaps)
                    {
                        if (!Xaps.IsWillStop)
                        {
                            Xaps.InstallSelectedXap(item);
                            IncreaseProgressBar();
                        }
                        else
                        {
                            showMessage(LocalizedStrings.str_operationstopped,true);
                            Xaps.IsWillStop = false;
                            break;
                        }
                    }
                    isOperating = false;
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_notconnect, true);
            }
        }

        private void UninstallXap(Xap _xap)
        {
            if (_device.Connected)
            {
                if (isOperating == false)
                {
                    isOperating = true;
                    ChangeProgressBarIndeterminate(true);
                    Xaps.UninstallSelectedXap(_xap);
                    ChangeProgressBarIndeterminate(false);
                    isOperating = false;
                    Xaps.IsWillStop = false;
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_installfailed + ": " + LocalizedStrings.str_notconnect, true);
            }

        }

        private void UninstallXaps(ObservableCollection<Xap> _xaps)
        {
            if (_device.Connected)
            {
                if (!isOperating)
                {
                    isOperating = true;
                    foreach (Xap item in _xaps)
                    {
                        if (!Xaps.IsWillStop)
                        {
                            Xaps.UninstallSelectedXap(item);
                            IncreaseProgressBar();
                        }
                        else
                        {
                            showMessage(LocalizedStrings.str_operationstopped, true);
                            Xaps.IsWillStop = false;
                            break;
                        }
                    }
                    isOperating = false;
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_notconnect, true);
            }
        }

        private void ConnectViaWpc()
        {
            bool isWpconnectOk = false;
            if (wpconnect_Path == "")
            {
                showMessage(LocalizedStrings.str_wpconnectpathnotdefine,true);
                initiateWpconnectPath();
            }
            else
            {
                if (IsZuneRunning() == false)
                {
                    showMessage(LocalizedStrings.str_launchingwpc + "...", true);
                    try
                    {
                        showMessage(LocalizedStrings.str_waitingforwpc, true);
                        Process p = new Process()
                        {
                            StartInfo =
                            {
                                FileName = wpconnect_Path,
                                UseShellExecute = false,
                                CreateNoWindow = true,
                            }
                        };
                        p.Start();
                        p.WaitForExit();
                        if (p.ExitCode.ToString() == "0")
                        {
                            isWpconnectOk = true;
                            showMessage(LocalizedStrings.str_wpconnectconnected + "!", true);
                        }
                        else
                        {
                            showMessage(LocalizedStrings.str_wpconnectnotconnected + "!", true);
                        }
                    }
                    catch (Exception ex)
                    {
                        showMessage(ex.Message.ToString(), true);
                        wpconnect_Path = "";
                        initiateWpconnectPath();
                    }
                }
                else
                {
                    showMessage(LocalizedStrings.str_wpconnectwontlaunch, true);
                }
            }

            if (isWpconnectOk && !IsZuneRunning())
            {
                showMessage(LocalizedStrings.str_connectingviawpc + "...", true);
                _device.Connect();
                //showMessage(_device.StatusMessage, true);
            }
        }

        private void Connect()
        {
            if (!isOperating)
            {
                isOperating = true;
                ChangeProgressBarIndeterminate(true);
                _device.Connect();
                if (!_device.Connected)
                {
                    //showMessage(LocalizedStrings.str_failedinconnecting + " " + CurrentDeviceName, true);
                    if (EzDeploy.Properties.Settings.Default.auto_Wpconnect == true &&_device.ExceptionMessage!="0x00000000")
                    {
                        ConnectViaWpc();
                    }
                }
                ChangeProgressBarIndeterminate(false);
                isOperating = false;
            }
            else
            {
                showMessage(LocalizedStrings.str_waitForOperationDone, true);
            }
        }

        #endregion

        #region WPConnect & Zune Path Operation

        private void initiateWpconnectPath()
        {
            if (wpconnect_Path == "")
            {
                if (Tools.Detect3264() == "64")
                {
                    wpconnect_Path = @"WPConnect\64\WPConnect.exe";
                }
                else
                {
                    wpconnect_Path = @"WPConnect\86\WPConnect.exe";
                }
            }
        }

        private void initiateZunePath()
        {
            if (zune_Path == "")
            {
                zune_Path = @"C:\Program Files\Zune\Zune.exe";
            }
        }

        private void saveWpconnectPath(string filepath)
        {
            wpconnect_Path = filepath;
            showMessage("\n" + wpconnect_Path, false);
        }

        private void saveZunePath(string filepath)
        {
            zune_Path = filepath;
            showMessage(LocalizedStrings.str_ZunePathSaved+ "\n" + zune_Path, false);
        }

        #endregion

        #region IsoStorage

        private void treeIsoStore_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            RemoteAppIsoStoreItem item = treeIsoStore.SelectedItem as RemoteAppIsoStoreItem;

            if (item == null)
                return;

            item.Update();

            stackFileProperties.DataContext = item.RemoteFile;
        }

        private void treeIsoStore_Expanded(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem item = e.OriginalSource as TreeViewItem;

                if (item.Items.Count == 1)
                {
                    FakeRemoteAppIsoStoreItem fake = item.Items[0] as FakeRemoteAppIsoStoreItem;

                    if (fake != null)
                    {
                        fake.Parent.Update();
                    }

                }
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
        }

        #endregion

        #region Other

        private bool IsZuneRunning()
        {
            bool result = false;
            foreach (Process singleProc in Process.GetProcesses())
            {
                if (singleProc.ProcessName.ToLower() == "zune")
                {
                    showMessage(LocalizedStrings.str_ZuneIsRunning, true);
                    result = true;
                    break;
                }
            }
            return result;
        }

        private void ModifyXap(Xap _xap)
        {
            try
            {
                if (_xap.Modify())
                {
                    ModifiedXaps.Add(_xap);
                    showMessage(_xap.Name + LocalizedStrings.str_SaveAsDone, true);

                }
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
            
        }

        private void ModifyAllXaps()
        {
            foreach (Xap _xap in Xaps)
            {
                if (Xaps.IsWillStop==false)
                {
                    ModifyXap(_xap);
                }
                else
                {
                    showMessage(LocalizedStrings.str_operationstopped, true);
                    Xaps.IsWillStop = false;
                    break;
                }
            }
        }

        private void DeleteAllModifiedXaps()
        {
            try
            {
                foreach (Xap _xap in ModifiedXaps)
                {
                    File.Delete(_xap.FilePath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void GetAppInfo(Xap _xap)
        {
            Stream iconpath = null;
            Stream bgIconpath = null;
            if (_xap.IsIconUpdated)
            {
                iconpath = File.OpenRead(_xap.NewIconPath);
            }
            else
            {
                iconpath = _xap.IconPath;
            }

            if (_xap.IsBgIconUpdated)
            {
                bgIconpath = File.OpenRead(_xap.NewBgIconPath);
            }
            else
            {
                bgIconpath = _xap.BgIconPath;
            }

            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                img_XapIconInSettingPanel.Source = Tools.ConvertFromStreamToBitmapImage(iconpath);
                img_XapBgIconInSettingPanel.Source = Tools.ConvertFromStreamToBitmapImage(bgIconpath);

                textBox_AppNameInSettingPanel.Text = _xap.willSetAppName;
                textBox_AuthorInSettingPanel.Text = _xap.willSetAuthor;
                textBox_AppDesInSettingPanel.Text = _xap.willSetDes;
                textBox_SubTitleInSettingPanel.Text = _xap.willSetSubTitle;

                txtAppNameinFilePanel.Text = _xap.Name;
                txtXapVersion.Text = _xap.Version;

                tgs_IsInSetting.IsChecked = _xap.IsInSetting;
                tgl_IsResumable.IsChecked = _xap.IsResumable;
            });
        }

        private void ChangeLanguage(string culture)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture =
            new System.Globalization.CultureInfo(culture);
            System.Threading.Thread.CurrentThread.CurrentCulture =
            new System.Globalization.CultureInfo(culture);

            // Reload all the merged dictionaries to reset the resources.
            List<Uri> dictionaryList = new List<Uri>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                if (dictionary.Source.ToString()==@"/Language/Default.xaml")
                {
                    Application.Current.Resources.MergedDictionaries.Remove(dictionary);
                    break;
                }
                dictionaryList.Add(dictionary.Source);
            }
            //Application.Current.Resources.MergedDictionaries.Clear();
            foreach (Uri uri in dictionaryList)
            {
                ResourceDictionary resourceDictionary1 = new ResourceDictionary();
                resourceDictionary1.Source = uri;
                Application.Current.Resources.MergedDictionaries.Add(resourceDictionary1);
            }
        }

        private void LoadAssembly()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (_, args) =>
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                String resourceName = asm.GetName().Name + "." + new AssemblyName(args.Name).Name + ".dll.gz";
                using (var stream = asm.GetManifestResourceStream(resourceName))
                {
                    if (stream != null)
                    {
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            GZipStream decompress = new GZipStream(stream, CompressionMode.Decompress);
                            decompress.CopyTo(memStream);
                            return Assembly.Load(memStream.GetBuffer());
                        }
                    }
                    else return null;
                }
            };
        }

        private void Storyboard_Completed(object sender, EventArgs e)
        {
            try
            {
                onGoing = false;
                Xaps.RemoveAt(remIndex);//问题：这一句会报错，不知道怎样解决，故将后面的语句移动到Catch中执行
                if (Xaps.Count > 0)
                {
                    if (remIndex >= Xaps.Count)
                        listBox_InstallingXaps.SelectedIndex = Xaps.Count - 1;
                    else
                        listBox_InstallingXaps.SelectedIndex = remIndex;
                }
                else
                {
                    listBox_InstallingXaps.SelectedIndex = -1;
                }
            }
            catch 
            {
                if (Xaps.Count > 0)
                {
                    if (remIndex >= Xaps.Count)
                        listBox_InstallingXaps.SelectedIndex = Xaps.Count - 1;
                    else
                        listBox_InstallingXaps.SelectedIndex = remIndex;
                }
            }
        }

        private void Storyboard_Clear_Completed(object sender, EventArgs e)
        {
            try
            {
                Xaps.Clear();
                IsClearing = false;
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
        }

        private void InitialLanguage()
        {
            LocalizedStrings.LoadLocalizedString();
        }

        private void Initial()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                this.DataContext = this;

                Device = new WindowsPhoneDevice();
                Xaps = new ListedXaps(_device);
                ModifiedXaps = new ListedXaps();

                Device.PropertyChanged += new PropertyChangedEventHandler(Device_PropertyChanged);
                Xaps.PropertyChanged += new PropertyChangedEventHandler(Xaps_PropertyChanged);

                InitialLanguage();

                initiateWpconnectPath();
                initiateZunePath();

                checkIsAutoConnect();
            });
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (Application.Current.Properties["ArbitraryArgName0"] != null)
            {
                int i = 0;
                while (true)
                {
                    if (Application.Current.Properties["ArbitraryArgName" + i.ToString()] == null)
                    {
                        break;
                    }
                    string path = Application.Current.Properties["ArbitraryArgName" + i.ToString()].ToString();
                    switch (path)
                    {
                        case "-quiet":
                            App.Current.MainWindow.Visibility = Visibility.Collapsed;
                            isQuietInstal = true;
                            showMessage("开启安静模式", true);
                            break;
                        default:
                            sortInputFile(path);
                            showMessage(path, true);
                            break;
                    }
                    i++;
                }
                if (isQuietInstal == true)
                {
                    showMessage(isQuietInstal.ToString(), true);
                    QuietInstall();
                }
            }
        }

        private void QuietInstall()
        {
            System.Console.WriteLine("开启安静模式");
            task_Connect = new Task(() => Connect());
            task_SmartInstall = task_Connect.ContinueWith((t) => InstallXaps(Xaps));
            Task task_Close = task_SmartInstall.ContinueWith((t) =>
                {
                    this.Dispatcher.Invoke((ThreadStart)delegate
                    {
                        Application.Current.Shutdown();
                    });
                });
            task_Connect.Start();
        }

        private void sortInputFile(object state)
        {
            string filepath = (string)state;
            try
            {
                string fileNameExt, fileExt;
                fileNameExt = FileOpration.GetFileNameExtFromPath(filepath);
                fileExt = FileOpration.GetFileExtFromPath(filepath);

                if (fileExt.ToLower() == "xap")
                {
                    //Task.Factory.StartNew(() => getXapInfo(filepath));
                    getXapInfo(filepath);
                }
                else if (fileNameExt.ToLower() == "zune.exe")
                {
                    //Task.Factory.StartNew(() => saveZunePath(filepath));
                    saveZunePath(filepath);
                }
                else if (fileNameExt.ToLower() == "wpconnect.exe")
                {
                    //Task.Factory.StartNew(() => saveWpconnectPath(filepath));
                    saveWpconnectPath(filepath);
                }
            }
            catch (Exception ex)
            {
                showMessage(ex.Message,true);
            }
            
        }

        private void checkIsAutoConnect()
        {
            if (EzDeploy.Properties.Settings.Default.ConnectWhenStartUP)
            {
                try
                {
                    task_Connect = new Task(() => Connect());
                    task_Connect.Start();
                }
                catch (Exception ex)
                {
                    showMessage(LocalizedStrings.str_failedinconnecting+": " + ex.Message, true);
                }
            }
        }

        private void addXapIfNotExisted(Xap _xap)
        {
            int temp = 0;
            try
            {
                foreach (Xap item in Xaps)
                {
                    if (item.FilePath == _xap.FilePath)
                    {
                        listBox_InstallingXaps.SelectedIndex = Xaps.IndexOf(item);
                        var container = listBox_InstallingXaps.ItemContainerGenerator.ContainerFromIndex(listBox_InstallingXaps.SelectedIndex);
                        var grid = GetChild<Grid>(container);
                        var storyboard = this.FindResource("listBoxItem_Existed") as Storyboard;
                        Storyboard.SetTarget(storyboard, grid);
                        remIndex = listBox_InstallingXaps.SelectedIndex;
                        storyboard.Begin();
                        temp++;
                        break;
                    }
                }
                if (temp == 0)
                {
                    Xaps.Add(_xap);
                }
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
            
        }

        private void getXapInfo(string filepath)
        {
            try
            {
                this.Dispatcher.Invoke((ThreadStart)delegate
                {
                    FileInfoPanel.IsExpanded = true;
                    xap = new Xap(filepath.Trim());
                    addXapIfNotExisted(xap);
                });
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
            
        }

        private void loadAppList()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                listBox_Apps.ItemsSource = Device.InstalledApplications;
            });
        }

        private void loadIsoList()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                treeIsoStore.ItemsSource = Device.RemoteIsoStores;
            });
        }

        private void showMessage(string msg, bool isAdd)
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                StatusPanel.IsExpanded = true;
                if (isAdd)
                {
                    txtStatus.Text += msg + "\n";
                }
                else
                {
                    txtStatus.Text = msg + "\n";
                }
            });
        }

        private void clearMessage()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                txtStatus.Text = "";
            });
        }

        public T GetChild<T>(DependencyObject obj) where T : DependencyObject
        {
            DependencyObject child = null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child.GetType() == typeof(T))
                    break;
                else if (child != null)
                {
                    child = GetChild<T>(child);
                    if (child != null && child.GetType() == typeof(T))
                        break;
                }
            }
            return child as T;
        }

        #endregion

        #region UI

        #region MainWindow

        private void window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                if (isOperating)
                {
                    Xaps.IsWillStop = true;
                    showMessage(LocalizedStrings.str_operationwillstop, true);
                }
                else
                {
                    StatusPanel.IsExpanded = false;
                    FileInfoPanel.IsExpanded = false;
                    SettingPanel.IsExpanded = false;
                    AppsPanel.IsExpanded = false;
                    MoreModifySettingsPanel.IsExpanded = false;
                }
            }
        }

        private void MainWindow_DragEnter(object sender, System.Windows.DragEventArgs e)
        {

        }

        private void MainWindow_Drop(object sender, System.Windows.DragEventArgs e)
        {
            int i = 0;
            //不能将“string filepath;"添加到 while 外面，否则在拖入多个文件时会报错。
            //string filepath;  -->这样是不行的
            while (true)
            {
                string filepath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(i).ToString();

                if (filepath == null)
                {
                    break;
                }

                i++;
                //Task.Factory.StartNew(() => sortInputFile(filepath));
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.sortInputFile), filepath);
            }
        }

        private void MainWindow_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        }

        private void MainWindow_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (!(StatusPanel.IsExpanded || SettingPanel.IsExpanded || AppsPanel.IsExpanded||FileInfoPanel.IsExpanded))
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    this.DragMove();
                }
                return;
            }
        }

        private void Floor_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
            return;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            showMessage(LocalizedStrings.str_Disconnecting, true);
            _device.Disconnect();
            showMessage(_device.StatusMessage, true);
            Application.Current.Shutdown();
        }

        private void btn_Minimize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        #endregion

        #region AppsPanel

        private void btn_Kill_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                if (CurSelectedInstalledApp != null)
                    //if (CurSelectedInstalledApp.RemoteApplication.IsRunning())
                    if (true)
                    {
                        //showMessage("准备结束程序"+CurSelectedInstalledApp.Name,true);
                        Task.Factory.StartNew(() =>
                        {
                            CurSelectedInstalledApp.RemoteApplication.TerminateRunningInstances();
                        });
                    }
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }

        }

        private void btn_Launch_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                if (CurSelectedInstalledApp != null)
                    CurSelectedInstalledApp.RemoteApplication.Launch();
            }
            catch (Exception ex)
            {
                showMessage(LocalizedStrings.str_LaunchingFailed + ex.Message, false);
            }

        }

        private void btn_UnistallFromAppsPanel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                Task task_Unistall = new Task(() =>
                {
                    if (CurSelectedInstalledApp != null)
                    {
                        showMessage(LocalizedStrings.str_uninstalling + CurSelectedInstalledApp.Name, false);

                        CurSelectedInstalledApp.RemoteApplication.Uninstall();

                        showMessage(LocalizedStrings.str_uninstalled, false);

                        _device.RefreshInstalledApps();
                    }
                });
                if (AppsPanel.IsExpanded)
                {
                    //refreash AppList when AppsPanel is expanded 
                    var task_loadAppList = task_Unistall.ContinueWith((t) => loadAppList());
                }
                task_Unistall.Start();
            }
            catch (Exception ex)
            {
                showMessage(LocalizedStrings.str_UnistalingFailed + ex.Message, false);
            }

        }

        private void btn_ShowAppsPanel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Task.Factory.StartNew(() => loadAppList());
            AppsPanel.IsExpanded = true;
        }

        private void btn_OpenIsoStorage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Task.Factory.StartNew(() => loadIsoList());
        }

        #endregion

        #region SettingPanel

        private void btn_OpenWpc_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            clearMessage();
            Task task = new Task(() => ConnectViaWpc());
            task.Start();
        }

        private void btn_OpenZune_Click(object sender, RoutedEventArgs e)
        {
            clearMessage();
            try
            {
                ProcessStartInfo procInfo = new ProcessStartInfo(zune_Path);
                Process procBatch = Process.Start(procInfo);
            }
            catch (Exception ex)
            {
                showMessage(ex.Message.ToString(), true);
                zune_Path = "";
                initiateZunePath();
            }
        
        }

        private void btn_About_Click(object sender, RoutedEventArgs e)
        {
            showMessage("该程序由Ornithopter编写，使用了Oren Nachman的WindowsPhone.Tools和Eric Jensen的Toggle Switch Control Library\n在使用之前，建议把WPConnect.exe和Zune.exe拖入程序窗口以保存文件路径，以后部署xap时，可以不用打开Zune程序，打开WPConnect即可\n联系我:\nQQ:233355215  Email:yhd4711499@live.com\n感谢：longhronshen\n版本:"+ _version, false);
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (!isOperating)
            {
                clearMessage();
                ClearProgressBarValue();
                try
                {
                    task_Connect = new Task(() => Connect());
                    task_Connect.Start();
                }
                catch (Exception ex)
                {
                    showMessage(ex.Message, false);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_waitForOperationDone, true);
            }
        }

        #region ComboBox

        private void comboBox_deviceChoose_onSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                //ComboBox temp = sender as ComboBox;
                //CurrentDeviceConnectControl.Device.CurrentDevice = (Microsoft.SmartDevice.Connectivity.Device)temp.SelectedItem;
                CurrentDeviceName = (sender as ComboBox).SelectedItem.ToString();
                txtDevice.Text = LocalizedStrings.str_device+": " + CurrentDeviceName;
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
        }

        #endregion

        #region ToggleSwitch

        private void tgl_ConWhenStart_Unchecked(object sender, RoutedEventArgs e)
        {
            EzDeploy.Properties.Settings.Default.ConnectWhenStartUP = tgl_ConWhenStart.IsChecked;
            EzDeploy.Properties.Settings.Default.Save();
        }

        private void tgl_AutoWpconnect_onCheckChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            EzDeploy.Properties.Settings.Default.auto_Wpconnect = tgl_AutoWpconnect.IsChecked;
            EzDeploy.Properties.Settings.Default.Save();
        }

        #endregion

        #endregion

        #region FileInfoPanel

        private void textBlock_Resume_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            clearMessage();
            showMessage(LocalizedStrings.str_ResumeHint, true);
        }

        private void textBlock_InSetting_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            clearMessage();
            showMessage(LocalizedStrings.str_InSettingHint, true);
        }

        private void FileInfoPanel_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
        }

        private void btn_Stop_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (isOperating)
            {
                showMessage(LocalizedStrings.str_operationwillstop, true);
                Xaps.IsWillStop = true;
            }
            else
            {
                showMessage(LocalizedStrings.str_nooperation, true);
            }
        }

        private void btn_SmartInstallOne_Click(object sender, RoutedEventArgs e)
        {
            if (listBox_InstallingXaps.SelectedIndex != -1)
            {
                if (!isOperating)
                {
                    clearMessage();
                    ClearProgressBarValue();
                    task_Connect = new Task(() => Connect());
                    task_SmartInstall = task_Connect.ContinueWith((t) => InstallXap(selectedXap));
                    if (AppsPanel.IsExpanded)
                    {
                        var task_loadAppList = task_SmartInstall.ContinueWith((t) => loadAppList());
                    }
                    task_Connect.Start();
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_selectxapfile, false);
            }
        }

        private void btn_UnistallOne_Click(object sender, RoutedEventArgs e)
        {
            if (listBox_InstallingXaps.SelectedIndex != -1)
            {
                if (!isOperating)
                {
                    clearMessage();
                    ClearProgressBarValue();
                    task_Connect = new Task(() => Connect());
                    task_Unistall = task_Connect.ContinueWith((t) => UninstallXap(selectedXap));
                    if (AppsPanel.IsExpanded)
                    {
                        var task_loadAppList = task_Unistall.ContinueWith((t) => loadAppList());
                    }
                    task_Connect.Start();
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_selectxapfile, false);
            }
        }

        private void btn_DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            if (listBox_InstallingXaps.SelectedIndex == -1 || onGoing)
            {
                return;
            }

            Task.Factory.StartNew(() =>
            {
                this.Dispatcher.Invoke((ThreadStart)delegate
                {
                    var container = listBox_InstallingXaps.ItemContainerGenerator.ContainerFromIndex(listBox_InstallingXaps.SelectedIndex);
                    var text = GetChild<TextBlock>(container);
                    var grid = GetChild<Grid>(container);
                    var storyboard = this.FindResource("storyboard_Unload") as Storyboard;
                    Storyboard.SetTarget(storyboard, grid);

                    onGoing = true;
                    remIndex = listBox_InstallingXaps.SelectedIndex;
                    //animtaion begin
                    storyboard.Begin();
                });
            });
        }

        private void btn_SmartInstall_Click(object sender, RoutedEventArgs e)
        {
            if (Xaps.Count != 0)
            {
                if (!isOperating)
                {
                    clearMessage();
                    ClearProgressBarValue();
                    task_Connect = new Task(() => Connect());
                    if (Xaps.Count==1)
                    {
                        task_SmartInstall = task_Connect.ContinueWith((t) => InstallXap(Xaps[0]));
                    }
                    else
                    {
                        task_SmartInstall = task_Connect.ContinueWith((t) => InstallXaps(Xaps));
                    }
                    if (AppsPanel.IsExpanded)
                    {
                        var task_loadAppList = task_SmartInstall.ContinueWith((t) => loadAppList());
                    }
                    task_Connect.Start();
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_dropxapfile, false);
            }
        }

        private void btn_Unistall_Click(object sender, RoutedEventArgs e)
        {
            if (Xaps.Count != 0)
            {  
                if (!isOperating)
                {
                    clearMessage();
                    ClearProgressBarValue();
                    task_Connect = new Task(() => Connect());

                    if (Xaps.Count==1)
                    {
                        task_Unistall = task_Connect.ContinueWith((t) => UninstallXap(Xaps[0]));
                    }
                    else
                    {
                        task_Unistall = task_Connect.ContinueWith((t) => UninstallXaps(Xaps));
                    }
                    
                    if (AppsPanel.IsExpanded)
                    {
                        var task_loadAppList = task_Unistall.ContinueWith((t) => loadAppList());
                    }
                    task_Connect.Start();
                }
                else
                {
                    showMessage(LocalizedStrings.str_waitForOperationDone, true);
                }
            }
            else
            {
                showMessage(LocalizedStrings.str_dropxapfile, false);
            }
        }

        private void btn_ClearFiles_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (IsClearing)
                return;

            IsClearing = true;
            xap = null;
            txtAppNameinFilePanel.Text = LocalizedStrings.str_ChooseAXapFile;
            txtXapVersion.Text = null;
            try
            {
                Task.Factory.StartNew(() =>
                {
                    this.Dispatcher.Invoke((ThreadStart)delegate
                    {
                        for (int i = 0; i < Xaps.Count; i++)
                        {
                            try
                            {
                                listBox_InstallingXaps.SelectedIndex = i;
                                var container = listBox_InstallingXaps.ItemContainerGenerator.ContainerFromIndex(listBox_InstallingXaps.SelectedIndex);
                                var grid = GetChild<Grid>(container);
                                var storyboard = this.FindResource("storyboard_Clear") as Storyboard;
                                Storyboard.SetTarget(storyboard, grid);
                                storyboard.Begin();
                            }
                            catch (Exception)
                            {
                                //showMessage(ex1.Message, true);
                            }
                        }
                        IsClearing = false;
                        listBox_InstallingXaps.SelectedIndex = -1;
                        DeleteAllModifiedXaps();
                    });
                });
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }
        }

        private void listBox_InstallingXaps_OnSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (IsClearing)
            {
                return;
            }
            else
            {
                if (listBox_InstallingXaps.SelectedIndex==-1)
                {
                    tgl_IsResumable.IsEnabled = false;
                    tgs_IsInSetting.IsEnabled = false;
                    selectedXap = null;
                    txtAppNameinFilePanel.Text = LocalizedStrings.str_ChooseAXapFile;
                    txtXapVersion.Text = null;
                    return;
                }
                else
                {
                    tgl_IsResumable.IsEnabled = true;
                    tgs_IsInSetting.IsEnabled = true;
                    Task.Factory.StartNew(() =>
                        {
                            GetAppInfo(selectedXap);
                        });
                }
                
            }
        }

        private void tgs_IsInSetting_OnChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (selectedXap!=null)
            {
                if (tgs_IsInSetting.IsChecked == true)
                {
                    selectedXap.isWillSetIntoSettings = true;
                }
                else
                {
                    selectedXap.isWillSetIntoSettings = false;
                }
            }
        }

        private void tgl_IsResumable_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (selectedXap!=null)
            {
                if (tgl_IsResumable.IsChecked == true)
                {
                    selectedXap.isWillSetIntoResumalbe = true;
                }
                else
                {
                    selectedXap.isWillSetIntoResumalbe = false;
                }
            }
        }

        private void btn_SaveAsXap_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!isOperating)
            {
                clearMessage();
                if (listBox_InstallingXaps.SelectedIndex == -1)
                {
                    showMessage(LocalizedStrings.str_ChooseAXapFile, true);
                    return;
                }
                pgb_Install1.IsIndeterminate = true;
                isOperating = true;
                Task t1 = Task.Factory.StartNew(() => ModifyXap(selectedXap));
                Task t2 = t1.ContinueWith((t) =>
                {
                    ChangeProgressBarIndeterminate(true);
                    isOperating = false;
                });
            }
            else
            {
                showMessage(LocalizedStrings.str_waitForOperationDone, true);
            }
        }

        private void btn_MoreModifySettings_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MoreModifySettingsPanel.IsExpanded = true;
        }

        private void btn_ModifyAll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!isOperating)
            {
                clearMessage();
                if (Xaps.Count != 0)
                {
                    ChangeProgressBarIndeterminate(true);
                    isOperating = true;
                    Task task = new Task(() => ModifyAllXaps());
                    Task task2 = task.ContinueWith((t) =>
                    {
                        ChangeProgressBarIndeterminate(false);
                        isOperating = false;
                    });
                    task.Start();
                }
                else
                {
                    showMessage(LocalizedStrings.str_dropxapfile, true);
                }      
            }
            else
            {
                showMessage(LocalizedStrings.str_waitForOperationDone, true);
            }
        }

        #endregion

        #region MoreInfoPanel

        private void canvas_XapIcon_Drop(object sender, System.Windows.DragEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                string filepath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                selectedXap.NewIconPath = filepath;
                GetAppInfo(selectedXap);
            });
        }

        private void canvas_XapBgIcon_Drop(object sender, System.Windows.DragEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                string filepath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                selectedXap.NewBgIconPath = filepath;
                GetAppInfo(selectedXap);
            });
        }

        private void btn_SaveAppInfo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (selectedXap != null)
            {
                try
                {
                    selectedXap.willSetAppName = textBox_AppNameInSettingPanel.Text;
                    selectedXap.willSetAuthor = textBox_AuthorInSettingPanel.Text;
                    selectedXap.willSetDes = textBox_AppDesInSettingPanel.Text;
                    selectedXap.willSetSubTitle = textBox_SubTitleInSettingPanel.Text;

                    selectedXap.IsIconWillUpdate = true;
                    selectedXap.IsBgIconWillUpdate = true;

                    selectedXap.IsInfoWillUpdate = true;

                    MoreModifySettingsPanel.IsExpanded = false;
                }
                catch (Exception ex)
                {
                    showMessage(ex.Message, true);
                }

            }
        }

        private void btn_ResetAppInfo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (selectedXap == null)
            {
                return;
            }
            try
            {
                Task.Factory.StartNew(() =>
                {
                    this.Dispatcher.Invoke((ThreadStart)delegate
                    {
                        selectedXap.willSetAppName = selectedXap.Name;
                        selectedXap.willSetAuthor = selectedXap.Author;
                        selectedXap.willSetDes = selectedXap.Description;
                        selectedXap.willSetSubTitle = selectedXap.SubTitle;

                        selectedXap.NewIconPath = null;
                        selectedXap.NewBgIconPath = null;
                        GetAppInfo(selectedXap);
                    });
                });
            }
            catch (Exception ex)
            {
                showMessage(ex.Message, true);
            }

        }

        #endregion

        #region ProgressBar
        private void ClearProgressBarValue()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                pgb_Install1.Value = 0;
            });
        }

        private void ChangeProgressBarIndeterminate(bool t)
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                pgb_Install1.IsIndeterminate = t;
            });
        }

        private void IncreaseProgressBar()
        {
            this.Dispatcher.Invoke((ThreadStart)delegate
            {
                pgb_Install1.Value++;
            });
        }
        #endregion

        #endregion

        # region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        #endregion

        #region Device_PropertyChanged

        void Device_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Connected")
            {
                if (_device.Connected)
                {
                }
                else
                {
                }
            }

            if (e.PropertyName == "StatusMessage")
            {
                showMessage(_device.StatusMessage,true);
            }
        }

        void Xaps_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "StatusMessage")
            {
                showMessage(Xaps.StatusMessage, true);
            }
        }
        #endregion

    }
}
